package com.app.biz.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.app.biz.domain.SysArea;
import com.app.biz.mapper.SysAreaMapper;
import com.app.biz.service.ISysAreaService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysAreaServiceImpl implements ISysAreaService {

    private final SysAreaMapper sysAreaMapper;

    public SysAreaServiceImpl(SysAreaMapper sysAreaMapper) {
        this.sysAreaMapper = sysAreaMapper;
    }

    @Override
    public List<Tree<String>> getAreaTree() {
        List<SysArea> list = sysAreaMapper.selectAreaLit();
        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        // 自定义属性名 都有默认值的
        treeNodeConfig.setWeightKey("code");
        treeNodeConfig.setIdKey("code");
        treeNodeConfig.setParentIdKey("parentCode");
        // 最大递归深度
        treeNodeConfig.setDeep(3);

        //转换器 (含义:找出父节点为字符串零的所有子节点, 并递归查找对应的子节点, 深度最多为 3)
        List<Tree<String>> treeNodes = TreeUtil.<SysArea, String>build(list, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getId());
                    tree.setParentId(treeNode.getCode());
                    tree.setWeight(treeNode.getCode());
                    tree.setName(treeNode.getName());
                    tree.setParentId(treeNode.getParentCode());
                });
        return treeNodes;
    }
}
